<template>
  <view class="pet-detail-page">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar" :style="{paddingTop: statusBarHeight + 'px'}">
      <view class="navbar-content">
        <view class="back-btn" @tap="goBack">
          <text class="iconfont">←</text>
        </view>
        <text class="navbar-title">宠物详情</text>
        <view class="more-btn" @tap="toggleEdit">
          <text class="iconfont">{{ isEdit ? '保存' : '编辑' }}</text>
        </view>
      </view>
    </view>

    <scroll-view scroll-y class="content-scroll">
      <!-- 宠物头像和名称（动态渲染，支持编辑） -->
      <view class="pet-header">
        <image :src="petData.avatar" 
               mode="aspectFill" 
               class="pet-avatar"></image>
        <text class="pet-name" v-if="!isEdit">{{ petData.name || '未知宠物' }}</text>
        <input v-if="isEdit" v-model="editData.name" class="pet-name-input" placeholder="请输入宠物名称" />
        <text class="pet-breed" v-if="!isEdit">{{ petData.breed || '未知品种' }}</text>
        <input v-if="isEdit" v-model="editData.breed" class="pet-breed-input" placeholder="请输入品种" />
      </view>

      <!-- 基本信息（动态渲染，支持编辑） -->
      <view class="info-card">
        <view class="card-header">
          <text class="card-title">📋 基本信息</text>
        </view>
        <view class="info-grid">
          <view class="info-item">
            <text class="info-label">宠物类型</text>
            <text class="info-value" v-if="!isEdit">{{ petData.type || '未知类型' }}</text>
            <input v-if="isEdit" v-model="editData.type" class="info-input" placeholder="如狗、猫等" />
          </view>
          <view class="info-item">
            <text class="info-label">性别</text>
            <picker v-if="isEdit" :range="genderOptions" :value="genderIndex" @change="onGenderChange" class="info-picker">
              {{ editData.gender || '请选择' }}
            </picker>
            <text class="info-value" v-else>
              {{ petData.gender || '未选择' }}
              {{ petData.isNeutered === 1 ? '(已绝育)' : '(未绝育)' }}
            </text>
          </view>
          <view class="info-item" v-if="isEdit">
            <text class="info-label">是否绝育</text>
            <picker :range="neuterOptions" :value="neuterIndex" @change="onNeuterChange" class="info-picker">
              {{ neuterOptions[neuterIndex] }}
            </picker>
          </view>
          <view class="info-item">
            <text class="info-label">出生日期</text>
            <text class="info-value" v-if="!isEdit">{{ formatDate(petData.birthday) }}</text>
            <picker v-if="isEdit" mode="date" :value="formatDate(editData.birthday)" @change="(e) => editData.birthday = e.detail.value" class="info-picker">
              {{ formatDate(editData.birthday) || '选择日期' }}
            </picker>
          </view>
          <view class="info-item">
            <text class="info-label">体重</text>
            <text class="info-value" v-if="!isEdit">{{ petData.weight || 0 }} kg</text>
            <input v-if="isEdit" v-model.number="editData.weight" type="number" class="info-input" placeholder="请输入体重" />
          </view>
          <view class="info-item">
            <text class="info-label">疫苗状态</text>
            <picker v-if="isEdit" :range="vaccineOptions" :value="vaccineIndex" @change="onVaccineChange" class="info-picker">
              {{ editData.vaccineStatus || '请选择' }}
            </picker>
            <text class="info-value" v-if="!isEdit">{{ petData.vaccineStatus || '未选择' }}</text> 
          </view>
          <view class="info-item">
            <text class="info-label">芯片编号</text>
            <text class="info-value" v-if="!isEdit">{{ petData.chipNumber || '无' }}</text>
            <input v-if="isEdit" v-model="editData.chipNumber" class="info-input" placeholder="请输入芯片编号" />
          </view>
          <view class="info-item">
            <text class="info-label">上次体检</text>
            <text class="info-value" v-if="!isEdit">{{ formatDate(petData.lastCheckup) || '无' }}</text>
            <picker v-if="isEdit" mode="date" :value="formatDate(editData.lastCheckup)" @change="(e) => editData.lastCheckup = e.detail.value" class="info-picker">
              {{ formatDate(editData.lastCheckup) || '选择日期' }}
            </picker>
          </view>
        </view>
      </view>
	  
	  <view class="info-card">
	    <view class="card-header">
	      <text class="card-title">📝 特殊说明</text>
	    </view>
	    <view class="notes-content">
	      <text class="notes-text" v-if="!isEdit">{{ petData.notes || '无特殊说明' }}</text>
	      <textarea v-if="isEdit" v-model="editData.notes" class="notes-textarea" placeholder="请输入特殊说明" />
	    </view>
	  </view>

      <!-- 健康数据图表（占位，可后续集成ECharts） -->
      <view class="info-card">
        <view class="card-header">
          <text class="card-title">💗 健康数据</text>
        </view>
        <view class="chart-placeholder">
          <text class="placeholder-text">健康数据趋势图</text>
          <text class="placeholder-hint">(需集成ECharts组件)</text>
        </view>
      </view>

      <!-- 操作按钮 -->
      <view class="action-buttons">
        <button class="action-btn primary-btn" @tap="addSchedule">
          <text class="btn-icon">📅</text>
          <text class="btn-text">添加日程</text>
        </button>
        <button class="action-btn secondary-btn">
          <text class="btn-icon">📋</text>
          <text class="btn-text">健康记录</text>
        </button>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, watch } from 'vue';
import { onLoad} from '@dcloudio/uni-app';
import petApi from '@/api/pet.js';

const statusBarHeight = ref(0);
const petData = ref({}); // 存储原始宠物详情数据
const editData = ref({
  name: '',
  breed: '',
  type: '',
  gender: '', // 初始空（未选择）
  isNeutered: 0,
  birthday: '',
  weight: 0,
  vaccineStatus: '', // 初始空（未选择）
  chipNumber: '',
  lastCheckup: '',
  notes: ''
}); // 存储编辑中的临时数据
const isEdit = ref(false); // 控制是否为编辑状态
const genderOptions = ref(['公', '母']);
const genderIndex = ref(-1); // 性别选择索引
const vaccineOptions = ref(['未接种', '部分接种', '已完成']);
const vaccineIndex = ref(-1); // 疫苗状态选择索引
// 绝育状态选项（和后端 0/1 对应）
const neuterOptions = ref(['未绝育', '已绝育']);
// 绝育状态选择索引（默认 0 → 未绝育）
const neuterIndex = ref(0);

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

// 格式化日期时间
const formatDatetime = (datetimeStr) => {
  if (!datetimeStr) return '';
  const date = new Date(datetimeStr);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

// 页面加载时获取路由参数并请求数据
onLoad((options) => {
  const systemInfo = uni.getSystemInfoSync();
  statusBarHeight.value = systemInfo.statusBarHeight || 0;

  const petId = options.id;
  if (petId) {
    fetchPetDetail(petId);
  }
});

// 请求宠物详情接口
const fetchPetDetail = async (petId) => {
  try {
    const res = await petApi.getPetById(petId);
    if (res.data.code === 200) {
      petData.value = res.data.data;
      editData.value = { ...res.data.data};
      neuterIndex.value = res.data.data.isNeutered;
      console.log("editData");
      console.log(editData.value);
      const data = res.data.data || {};
      genderIndex.value = data.gender ? genderOptions.value.indexOf(data.gender) : -1; // 无值则-1
      vaccineIndex.value = data.vaccineStatus ? vaccineOptions.value.indexOf(data.vaccineStatus) : -1; // 无值则-1
    } else {
      uni.showToast({ title: res.message || '获取宠物详情失败', icon: 'none' });
    }
  } catch (err) {
    console.error('获取宠物详情失败', err);
    uni.showToast({ title: '网络异常，请重试', icon: 'none' });
  }
};

// 切换编辑状态
const toggleEdit = async () => {
  if (isEdit.value) {
    await saveEdit();
  }
  isEdit.value = !isEdit.value;
};

// 保存编辑
const saveEdit = async () => {
  try {
    if (genderIndex.value !== -1) {
      editData.value.gender = genderOptions.value[genderIndex.value];
    } else {
      editData.value.gender = ''; // 未选择则设空
    }
    if (vaccineIndex.value !== -1) {
      editData.value.vaccineStatus = vaccineOptions.value[vaccineIndex.value];
    } else {
      editData.value.vaccineStatus = ''; // 未选择则设空
    }
    
    const res = await petApi.updatePet(editData.value);
    if (res.data.code === 200) {
      petData.value = { ...editData.value};
      console.log(petData.value);
      uni.showToast({ title: '保存成功' });
    } else {
      uni.showToast({ title: res.message || '保存失败', icon: 'none' });
    }
  } catch (err) {
    console.error('保存宠物信息失败', err);
    uni.showToast({ title: '网络异常，请重试', icon: 'none' });
  }
};

// 新增：性别选择器变更事件
const onGenderChange = (e) => {
  genderIndex.value = e.detail.value;
  editData.value.gender = genderOptions.value[genderIndex.value];
};

// 新增：疫苗状态选择器变更事件
const onVaccineChange = (e) => {
  vaccineIndex.value = e.detail.value;
  editData.value.vaccineStatus = vaccineOptions.value[vaccineIndex.value];
};

// 新增：绝育状态下拉框变更事件
const onNeuterChange = (e) => {
  neuterIndex.value = e.detail.value;
  // 关键修改：直接同步索引值（0/1），不转布尔
  editData.value.isNeutered = neuterIndex.value; 
};

const addSchedule = () => {
  uni.navigateTo({
    url: '/pages/schedule/schedule'
  });
};

const goBack = () => {
  uni.navigateBack();
};
</script>

<style scoped>
.pet-detail-page {
  min-height: 100vh;
  background: linear-gradient(to bottom, #89CFF020 0%, #F5F5F5 200rpx);
}

.custom-navbar {
  background: linear-gradient(135deg, #89CFF0 0%, #B7F0AD 100%);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

.navbar-content {
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 32rpx;
}

.back-btn,
.more-btn {
  width: 64rpx;
  height: 64rpx;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 36rpx;
  color: #5A7D9A;
}

.navbar-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #FFFFFF;
}

.content-scroll {
  height: 100vh;
  padding-top: calc(88rpx + var(--status-bar-height));
  padding-bottom: 120rpx;
}

.pet-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 48rpx 32rpx;
}

.pet-avatar {
  width: 200rpx;
  height: 200rpx;
  border-radius: 50%;
  border: 8rpx solid #FFFFFF;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
  margin-bottom: 24rpx;
}

.pet-name, .pet-name-input {
  font-size: 48rpx;
  font-weight: bold;
  color: #333333;
  margin-bottom: 8rpx;
}

.pet-name-input {
  width: 100%;
  text-align: center;
  border-bottom: 1rpx solid #eee;
}

.pet-breed, .pet-breed-input {
  font-size: 28rpx;
  color: #999999;
}

.pet-breed-input {
  width: 100%;
  text-align: center;
  border-bottom: 1rpx solid #eee;
}

.notes-content {
  padding: 16rpx 0;
}

.notes-text {
  font-size: 28rpx;
  color: #666666;
  line-height: 1.6;
}

.notes-textarea {
  width: 100%;
  min-height: 120rpx;
  font-size: 28rpx;
  color: #666666;
  line-height: 1.6;
  border: 1rpx solid #eee;
  border-radius: 8rpx;
  padding: 8rpx;
}

.info-card {
  background-color: #FFFFFF;
  border-radius: 24rpx;
  padding: 32rpx;
  margin: 0 32rpx 24rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
}

.card-header {
  margin-bottom: 24rpx;
}

.card-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 24rpx;
}

.info-item {
  display: flex;
  flex-direction: column;
}

.info-label {
  font-size: 24rpx;
  color: #999999;
  margin-bottom: 8rpx;
}

.info-value, .info-input, .info-picker {
  font-size: 28rpx;
  font-weight: 500;
  color: #333333;
}

.info-input {
  width: 100%;
  border-bottom: 1rpx solid #eee;
  padding-bottom: 8rpx;
}

.info-picker {
  width: 100%;
  border-bottom: 1rpx solid #eee;
  padding-bottom: 8rpx;
}

.chart-placeholder {
  height: 512rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #F8F9FA;
  border-radius: 16rpx;
}

.placeholder-text {
  font-size: 32rpx;
  color: #999999;
  margin-bottom: 8rpx;
}

.placeholder-hint {
  font-size: 24rpx;
  color: #CCCCCC;
}

.action-buttons {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 24rpx;
  padding: 0 32rpx;
  margin-bottom: 24rpx;
}

.action-btn {
  border-radius: 24rpx;
  padding: 24rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
  border: none;
  font-size: 28rpx;
}

.primary-btn {
  background-color: #89CFF0;
  color: #FFFFFF;
}

.secondary-btn {
  background-color: #B7F0AD;
  color: #5A7D9A;
}

.btn-icon {
  font-size: 32rpx;
}
</style>